package com.vote.controllers;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.vote.model.Option;
import com.vote.model.Question;
import com.vote.model.Questionnaire;
import com.vote.model.User;
import com.vote.services.QuestionnaireService;
import com.vote.utils.HostHelper;
import com.vote.utils.JSONTransform;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.ReqMapping;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class QuestionnaireController {

    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(QuestionnaireController.class);

    @Autowired
    QuestionnaireService questionnaireService;

    public String index() {
        return null;
    }

    public String createQuestionnaire(Invocation inv) {
        StringBuffer jb = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = inv.getRequest().getReader();
            while ((line = reader.readLine()) != null)
                jb.append(line);
        } catch (Exception e) { //report an error 
        }

        JSONObject jsonObject = JSONObject.fromObject(jb.toString());
        Questionnaire questionnaire = JSONTransform.JSON2Model(jsonObject);
        questionnaire.setOwnerId(1);
        try {
            //questionnaireService.insertQuestionnaire(questionnaire);
        } catch (Exception e) {
            e.printStackTrace();
            return "@fail";
        }
        return "@success";
    }
    
    @ReqMapping(path="getQuestionnaire-$qnid:\\d+")
    public Object getQuestionnaire(Invocation inv, @Param("qnid")int qnid){
        Questionnaire qn = questionnaireService.getQuestionnaireById(qnid);
        //User host = HostHelper.getHost(inv.getRequest());
        User host = new User();
        host.setUserId(1);
        if(qn == null){
            logger.info("user("+host.getUserId()+") get null questionnaire("+qnid+")");
            return null;
        }
        if(qn.getOwnerId() != host.getUserId()){
            logger.info("user("+host.getUserId()+") get questionnaire("+qnid+") for edit but not his questionnaire");
            return null;
        }
        JSONObject jo = JSONTransform.Model2JSON(qn);
        return jo;
    }
}
